# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
  def link_to_user(user)
    link_to(h(user.name), user_path(user)) unless user.guest?
  end
  
  def link_to_post(post, content = nil)
    content ||= smart_time_ago_in_words(post.created_at)
    link_to content, topic_post_path(post)
  end
  
  def cancel_button(url = nil)
    url ||= url_for :action => 'index'
    button_to_function 'Cancel', 'location=\'' + url + '\''
  end
  
  def smart_time_ago_in_words(from, to = Time.now)
    time = (to - from).abs
    if time < 1.minute then 'less than a minute ago'
    elsif time < 1.hour then pluralize((time/1.minute).round, 'minute') + ' ago'
    elsif time < 1.day then pluralize((time/1.hour).round, 'hour') + ' ago'
    elsif time < 1.year then from.strftime("%b #{from.day.ordinalize} %I:%M %p")
    else from.strftime("%b #{from.day.ordinalize}, %Y %I:%M %p")
    end
  end
  
  def format_post(text)
    text.gsub!(/\r\n|\n|\r/, "\n") # lets make them newlines crossplatform
    content_tag("p", auto_link(BBCode.new(text).to_html))
  end
  
  def action_links_for_post(post)
    links = []
    links << link_to('quote', new_post_path(:topic_id => post.topic, :quote_post_id => post)) if current_user.can_create_post? Post.new(:topic => post.topic)
    links << link_to('report', new_report_path(:post_id => post)) if current_user.can_create_report?
    links << link_to('edit', edit_post_path(post)) if current_user.can_update_post? post
    links << link_to('destroy', post_path(post), :confirm => 'Are you sure?', :method => 'delete') if current_user.can_destroy_post? post
    links.join ' | '
  end
  
  def forum_crumbs(forum)
    out = link_to_unless_current h(forum.name), forum_path(forum)
    while forum.parent
      forum = forum.parent
      out = link_to(h(forum.name), forum_path(forum)) + " &gt; " + out
    end
    out
  end
  
  def tabindexer
    @tabindex = @tabindex ? @tabindex.succ : 1
  end
  
end
